package me.chan.netty.rpc.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.netty.rpc.client.handler.RpcResponseMessageHandler;
import me.chan.netty.rpc.server.codec.ProtocolFrameDecoder;
import me.chan.netty.rpc.server.codec.SharableMessageCodec;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class RPCClientContext {

    private static Channel channel;

    private static ReentrantLock lock = new ReentrantLock();

//    public static void main(String[] args) {
//
//        initChannel();
//    }


    public static Channel getChannel() {
        if (channel != null)
            return channel;

        try {
            lock.lock();
            if (channel != null) {
                return channel;
            }
            channel = initChannel();
        } finally {
            lock.unlock();
        }

        return channel;
    }

    private static Channel initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
        SharableMessageCodec MSG_CODEC = new SharableMessageCodec();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // .addLast(new IdleStateHandler(0, 10, 0))
                                    // add heartbeat detector
                                    // .addLast(new MyChannelDuplexHandler())
                                    .addLast(new ProtocolFrameDecoder())
                                    .addLast(new LoggingHandler(LogLevel.DEBUG))
                                    .addLast(MSG_CODEC)
                                    .addLast(RPC_HANDLER);
                        }

                    });
            Channel channel = bootstrap.connect("127.0.0.1", 8080).sync().channel();
            // close the channel async
            channel.closeFuture().addListener( future -> {
                group.shutdownGracefully();
            });
            return channel;
            /*
            RpcRequestMessage message = new RpcRequestMessage();
            message.setSequenceId(1);
            message.setInterfaceName("me.chan.netty.rpc.server.service.HelloService");
            message.setMethodName("sayHello");
            message.setReturnType(String.class);
            message.setParameterTypes(new Class[]{String.class});
            message.setParameterValues(new Object[]{"2020 Tokyo Olympic Games"});
            ChannelFuture cf = channel.writeAndFlush(message);
            cf.addListener(listener -> {
               if (!listener.isSuccess()) {
                   log.error("error:", listener.cause());
               }
            });
            channel.closeFuture().sync();
            */
        } catch (Exception ex) {
            log.error("client error", ex);
        }

        return null;
    }


}
